﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using YiSha.Data.Repository;
using YiSha.Entity.Test;
using YiSha.Model.Param.Test;
using YiSha.Util.Extension;

namespace YiSha.Service.Test
{
    public class ProcessService : RepositoryFactory
    {

        #region 获取数据
        public async Task<List<ProcessEntity>> GetListJson(ProcessParam param)
        {
            var expression = ListFilter(param);
            var list = await this.BaseRepository().FindList(expression);
            return list.ToList();
        }
        #endregion

        #region 新增数据
        public async Task<int> Add(ProcessEntity processEntity)
        {
            return await this.BaseRepository().Insert(processEntity);
        }
        #endregion

        #region 私有方法
        private Expression<Func<ProcessEntity, bool>> ListFilter(ProcessParam param)
        {
            var expression = LinqExtensions.True<ProcessEntity>();

            // 如果传入了ID，则根据ID筛选
            if (param.Id.HasValue)
            {
                expression = expression.And(t => t.Id == param.Id.Value);
            }

            // 如果传入了用户ID，则根据用户ID筛选有权限的工序
            if (param.UserId.HasValue)
            {
                // 根据工序长ID筛选（每个工序指定一位工序长）
                expression = expression.And(t => t.UserId == param.UserId.Value);
            }

            // 如果传入了父级ID，则根据父级ID筛选工序
            if (param.ParentId.HasValue)
            {
                if (param.ParentIdIsEqual)
                {
                    expression = expression.And(t => t.ParentId == param.ParentId.Value);
                }
                else
                {
                    expression = expression.And(t => t.ParentId != param.ParentId.Value);
                }

            }

            // 如果传入了部门备注，则根据部门备注筛选有权限的工序
            if (!string.IsNullOrEmpty(param.DepartmentRemark))
            {
                expression = expression.And(t => t.DepartmentRemark == param.DepartmentRemark);
            }

            //查询顶级工序——父级Id为0
            if (param.IsTop)
            {
                expression = expression.And(t => t.ParentId == 0);
            }

            return expression;
        }
        #endregion

    }
}
